package com.boot.controller;

import com.boot.entity.*;
import com.boot.service.IPurchaseApplyService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采购执行Controller
 */
@Controller
@RequestMapping("/purchaseApply")
public class PurchaseApplyController {

    @Autowired
    private IPurchaseApplyService service;

    @RequestMapping("/list")
    public String getTenderList(String purchapplyStatus, String documentNumber, String supplierName,HttpServletRequest request, Integer pageIndex, Integer pageSize, Model model) {
        try {
            if (pageIndex == null) {
                pageIndex = 1;
            }
            if (pageSize == null) {
                pageSize = 6;
            }

            if ("all".equals(purchapplyStatus)) {
                purchapplyStatus = null;
            }
            if (StringUtils.isEmpty(purchapplyStatus)) {
                purchapplyStatus = null;
            }
            if (StringUtils.isEmpty(documentNumber)) {
                documentNumber = null;
            }
            if (StringUtils.isEmpty(supplierName)) {
                supplierName = null;
            }
            User user = (User) request.getSession().getAttribute("loginUser");
            if (user == null) {
                throw new RuntimeException("用户未登录");
            }
            if (StringUtils.isEmpty(user.getCompanyId())) {
                throw new RuntimeException("用户公司id为空 ");
            }

            PageHelper.startPage(pageIndex, pageSize);
            List<Map<String, Object>> purchaseReleaseList = service.getTenderList(purchapplyStatus, documentNumber, supplierName, user.getCompanyId());
            model.addAttribute("purchaseReleaseList", purchaseReleaseList);
            model.addAttribute("purchapplyStatus", purchapplyStatus);
            model.addAttribute("documentNumber", documentNumber);
            model.addAttribute("supplierName", supplierName);

            int count = service.getTenderListCount(purchapplyStatus, documentNumber, supplierName, user.getCompanyId());
            int pageNum = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
            model.addAttribute("count", count); //查询数量

            model.addAttribute("pageNum", pageNum); //分页数量
            model.addAttribute("currentPage", pageIndex); //当前页面
            model.addAttribute("pageSize", pageSize); //页面数据条数
            return "purchapplycheck";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }

    @RequestMapping("/list/purchaseRelease")
    public String getPurchaseReleaseList(String purchapplyStatus, String documentNumber, String supplierName, HttpServletRequest request, Integer pageIndex, Integer pageSize, Model model) {
        try {
            if (pageIndex == null) {
                pageIndex = 1;
            }
            if (pageSize == null) {
                pageSize = 6;
            }

            if ("all".equals(purchapplyStatus)) {
                purchapplyStatus = null;
            }
            if (StringUtils.isEmpty(purchapplyStatus)) {
                purchapplyStatus = null;
            }
            if (StringUtils.isEmpty(documentNumber)) {
                documentNumber = null;
            }
            if (StringUtils.isEmpty(supplierName)) {
                supplierName = null;
            }
            User user = (User) request.getSession().getAttribute("loginUser");
            if (user == null) {
                throw new RuntimeException("用户未登录");
            }
            if (StringUtils.isEmpty(user.getCompanyId())) {
                throw new RuntimeException("用户公司id为空 ");
            }

            PageHelper.startPage(pageIndex, pageSize);
            List<Map<String, Object>> purchaseReleaseList = service.getPurchaseReleaseList(purchapplyStatus, documentNumber, supplierName, user.getCompanyId());
            model.addAttribute("purchaseReleaseList", purchaseReleaseList);
            model.addAttribute("purchapplyStatus", purchapplyStatus);
            model.addAttribute("documentNumber", documentNumber);
            model.addAttribute("supplierName", supplierName);

            int count = service.getPurchaseReleaseCount(purchapplyStatus, documentNumber, supplierName, user.getCompanyId());
            int pageNum = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
            model.addAttribute("count", count); //查询数量

            model.addAttribute("pageNum", pageNum); //分页数量
            model.addAttribute("currentPage", pageIndex); //当前页面
            model.addAttribute("pageSize", pageSize); //页面数据条数
            return "purchaseRelease";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }

    @RequestMapping("/getPurchaseDetail/{tenderId}")
    public String getPurchaseDetail(@PathVariable("tenderId") Integer tenderId, Model model) {
        try {
            //采购信息
            Map<String, Object> purchaseMap = service.getPurchaseDetail(tenderId);
            //采购信息中id对应的name
            Map<String, Object> nameMap = service.getPurchaseDetaiName(tenderId);
            if (nameMap != null && !nameMap.isEmpty()) {
                purchaseMap.putAll(nameMap);
            }
            //煤质要求
            Map<String, Object> coalQualityMap = service.getCoalQualityMap(tenderId);
            //投标信息
            Map<String, Object> tenderDetailMap = service.getTenderDetail(tenderId);
            //投标信息中id对应的name
            Map<String, Object> tenderNameMap = service.getTenderDetailName(tenderId);
            if (tenderNameMap != null && !tenderNameMap.isEmpty()) {
                tenderDetailMap.putAll(tenderNameMap);
            }

            //审核记录
            List<Map<String, Object>> auditRecords = service.getTenderAuditList(tenderId);
            //创建记录
            Map<String, Object> createRecord = service.getTenderCreateInfo(tenderId);
            createRecord.put("operation", "创建");
            createRecord.put("check_opinion", "");
            createRecord.put("check_remark", "");
            auditRecords.add(0, createRecord);

            model.addAttribute("purchaseMap", purchaseMap);
            model.addAttribute("coalQualityMap", coalQualityMap);
            model.addAttribute("tenderDetailMap", tenderDetailMap);
            model.addAttribute("auditRecords", auditRecords);
            return "purchaseReleaseDetail";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }

    @RequestMapping("/getPurchaseDetail/auditTender")
    @ResponseBody
    public Object auditTender(TenderReview tenderReview, HttpServletRequest request, Model model) {
        Map<String, Object> map = new HashMap<>();
        try {
            User user = (User) request.getSession().getAttribute("loginUser");

            if (user == null) {
                map.put("msg", "用户信息为空");
                map.put("code", 601);
            } else if (!StringUtils.isEmpty(user.getId()) && !StringUtils.isEmpty(user.getCompanyId())) {
                tenderReview.setOperatorId(user.getId());
                if (user.getRole() == 2 || user.getRole() == 3) {
                    //插入记录
                    if (service.auditTender(tenderReview)) {
                        //更新投标表审核时间和状态
                        if(service.updateTenderStatus(tenderReview.getTenderId(),tenderReview.getCheckOpinion(),tenderReview.getOperationTime())){
                            map.put("msg", "审核成功");
                            map.put("code", 200);
                        }else {
                            map.put("msg","更新投标表状态失败");
                            map.put("code", 601);
                        }

                    } else {
                        map.put("msg", "审核失败");
                        map.put("code", 601);
                    }
                } else {
                    map.put("msg", "权限不足，无法审核");
                    map.put("code", 403);
                }
            }
            return map;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            map.put("msg", e.getMessage());
            map.put("code", 601);
            return e.getMessage();
        }
    }
}